import Vue from "vue";
import VueRouter from "vue-router";
import Layout from "../views/layout.vue";
import Login from "../views/login.vue";
import Detail from "../views/detail.vue";
import Register from "../views/register.vue";
import Article from "../views/article.vue";
import Collect from "../views/collect.vue";
import Like from "../views/like.vue";
import User from "../views/user.vue";
import { getToken } from "@/utils/storage";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    component: Layout,
    redirect: "/article",
    children: [
      {
        path: "article",
        component: Article,
      },
      {
        path: "collect",
        component: Collect,
      },
      {
        path: "like",
        component: Like,
      },
      {
        path: "user",
        component: User,
      },
    ],
  },
  {
    path: "/login",
    component: Login,
  },
  {
    path: "/detail",
    component: Detail,
  },
  {
    path: "/register",
    component: Register,
  },
];

const router = new VueRouter({
  routes,
});

//白名单
const whiteList = ["/login", "/register"];

//只要页面切换就会调用beforeEach
router.beforeEach((to, from, next) => {
  console.log(to);
  // console.log(from);
  const token = getToken();
  if (token || whiteList.includes(to.path)) {
    next();
  } else {
    next("/login");
  }
  /*
判断用户有没有token， 有token，直接放行·(有身份的人，想去哪就去哪~)
没有token (游客)，如果是白名单中的页面，直接放行
否则，无token (游客)，且在访问需要权限访问的页面，直接拦截到登录

to:去哪里
from:从哪里来
next 让不让你去 (去哪里)
只要调用了next()放行的意思
进行权限的判断，只有满足条件才放行*/
});
export default router;
